<template>
  <view class="appointment-record">
    <!-- 状态筛选标签 -->
    <scroll-view class="status-tabs" scroll-x>
      <view class="tabs-content">
        <view
          class="tab-item"
          :class="{ active: currentTab === item.value }"
          v-for="item in statusTabs"
          :key="item.value"
          @click="switchTab(item.value)"
        >
          <text class="tab-text">{{ item.label }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 时间筛选 -->
    <view class="time-filter-container">
      <view class="time-filter" @click="showTimePicker">
        <uni-icons type="calendar" size="16" color="#1890ff"></uni-icons>
        <text class="filter-text">{{ timeFilterText }}</text>
        <uni-icons type="bottom" size="12" color="#1890ff"></uni-icons>
      </view>
    </view>

    <!-- 记录列表 -->
    <scroll-view class="record-list" scroll-y refresher-enabled :refresher-triggered="refresherTriggered" @refresherrefresh="onRefresh">
      <view class="record-card" v-for="record in filteredRecords" :key="record.applyId">
        <view class="card-content">
          <!-- 左侧状态标签 -->
          <view
            class="status-badge"
            :class="
              record.auditStatus === '0'
                ? 'status-pending'
                : record.auditStatus === '1' || (record.auditStatus === '2' && record.checkStatus === '1' && record.qrColor === '0')
                ? 'status-approved'
                : record.auditStatus === '2' && record.checkStatus !== '1'
                ? 'status-inspection'
                : record.auditStatus === '3' || (record.checkStatus === '1' && record.qrColor === '2')
                ? 'status-rejected'
                : record.auditStatus === '4'
                ? 'status-expired'
                : 'status-pending'
            "
          >
            <uni-icons
              :type="
                record.auditStatus === '0'
                  ? 'time'
                  : record.auditStatus === '1' || (record.auditStatus === '2' && record.checkStatus === '1' && record.qrColor === '0')
                  ? 'checkmarkempty'
                  : record.auditStatus === '2' && record.checkStatus !== '1'
                  ? 'scan'
                  : record.auditStatus === '3' || (record.checkStatus === '1' && record.qrColor === '2')
                  ? 'closeempty'
                  : record.auditStatus === '4'
                  ? 'info'
                  : 'time'
              "
              size="14"
              color="#fff"
            ></uni-icons>
            <text class="status-text">{{
              record.auditStatus === '0'
                ? '待审核'
                : record.auditStatus === '1' || (record.auditStatus === '2' && record.checkStatus === '1' && record.qrColor === '0')
                ? '已通过'
                : record.auditStatus === '2' && record.checkStatus !== '1'
                ? '需抽检'
                : record.auditStatus === '3'
                ? '已驳回'
                : record.checkStatus === '1' && record.qrColor === '2'
                ? '抽检不合格'
                : record.auditStatus === '4'
                ? '已过期'
                : '待审核'
            }}</text>
          </view>

          <!-- 右上角操作按钮 -->
          <view class="action-buttons">
            <view class="action-btn detail-btn" @click="goToDetail(record)">
              <uni-icons type="list" size="18" color="#666"></uni-icons>
              <text class="btn-text">详情</text>
            </view>
            <view class="action-btn reapply-btn" @click="reApply(record)" v-if="canReApply(record.auditStatus)">
              <uni-icons type="refresh" size="18" color="#666"></uni-icons>
              <text class="btn-text">重新预约</text>
            </view>
            <view class="action-btn delete-btn" @click="deleteRecord(record)" v-if="canDelete(record.auditStatus)">
              <uni-icons type="trash" size="18" color="#ff4d4f"></uni-icons>
              <text class="btn-text">删除</text>
            </view>
          </view>

          <!-- 主要内容区域 -->
          <view class="main-content">
            <text class="record-number">{{ record.applyNo }}</text>
            <text class="market-name">{{ getMarketName(record) }}</text>
            <text class="product-info">{{ getProductType(record) }}</text>

            <view class="record-bottom">
              <text class="record-time">{{ formatDateTime(record.createTime) }}</text>
              <text class="product-quantity">产品数量：{{ record.totalAmount || '1' }}件</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredRecords.length === 0">
        <uni-icons type="list" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无预约记录</text>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && filteredRecords.length > 0" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
    </scroll-view>

    <!-- 时间选择弹窗 -->
    <uni-popup ref="timePopup" type="bottom" background-color="#f8f8f8">
      <view class="time-picker-popup">
        <view class="popup-header">
          <text class="cancel-btn" @click="closeTimePicker">取消</text>
          <text class="popup-title">选择时间范围</text>
          <text class="confirm-btn" @click="confirmTimeFilter">确定</text>
        </view>
        <view class="time-options">
          <view
            class="time-option"
            :class="{ active: tempTimeFilter === option.value }"
            v-for="option in timeOptions"
            :key="option.value"
            @click="selectTempTimeOption(option)"
          >
            <text class="option-text">{{ option.label }}</text>
            <view class="option-check" v-if="tempTimeFilter === option.value">
              <uni-icons type="checkmarkempty" size="18" color="#1890ff"></uni-icons>
            </view>
          </view>
        </view>

        <!-- 当前选择提示 -->
        <view class="current-selection" v-if="tempTimeFilter">
          <text class="selection-label">当前选择：</text>
          <text class="selection-value">{{ getTempFilterLabel() }}</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listAppointment, delAppointment } from '@/api/business/appointment.js';

export default {
  data() {
    return {
      currentTab: 'all',
      statusTabs: [
        { value: 'all', label: '全部' },
        { value: '0', label: '待审核' },
        { value: '1', label: '已通过' },
        { value: '3', label: '已驳回' },
        { value: '4', label: '已过期' },
      ],
      currentTimeFilter: '7days',
      timeFilterText: '近7天',
      tempTimeFilter: '7days', // 临时选择的时间筛选
      timeOptions: [
        { value: '7days', label: '近7天' },
        { value: '30days', label: '近30天' },
        { value: 'all', label: '全部时间' },
        { value: 'custom', label: '自定义时间' },
      ],
      recordList: [],
      filteredRecords: [],
      hasMore: true,
      page: 1,
      pageSize: 10,
      refresherTriggered: false, // 下拉刷新状态
    };
  },
  onLoad() {
    this.loadRecords();
  },
  methods: {
    // 加载预约记录
    async loadRecords() {
      try {
        // 获取商户ID，不设置默认值
        const merchantId = uni.getStorageSync('merchantId');

        // 构建查询参数
        const params = {
          pageNum: this.page,
          pageSize: this.pageSize,
        };

        // 如果有商户ID，添加到查询参数中
        if (merchantId) {
          params.merchantId = merchantId;
        }

        // 统一使用支持分页的接口
        const response = await listAppointment(params);

        if (response.code === 200) {
          const records = response.rows || response.data || [];
          console.log('加载到的记录数:', records.length);
          console.log('当前页码:', this.page);

          if (this.page === 1) {
            // 第一页，替换数据
            this.recordList = records;
          } else {
            // 追加数据
            this.recordList.push(...records);
          }

          // 判断是否还有更多数据
          this.hasMore = records.length === this.pageSize;

          console.log('总记录数:', this.recordList.length);
          console.log('是否还有更多:', this.hasMore);

          // 筛选记录
          this.filterRecords();
        }
      } catch (error) {
        console.error('加载预约记录失败:', error);
        this.recordList = [];
        this.filterRecords();
        uni.showToast({
          title: '加载记录失败',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    // 切换标签
    switchTab(value) {
      this.currentTab = value;
      this.page = 1;
      this.filterRecords();
    },

    // 筛选记录
    filterRecords() {
      console.log('开始筛选记录');
      console.log('原始记录列表长度:', this.recordList.length);
      console.log('当前状态筛选:', this.currentTab);
      console.log('当前时间筛选:', this.currentTimeFilter);

      let filtered = [...this.recordList]; // 创建副本

      // 按状态筛选
      if (this.currentTab !== 'all') {
        filtered = filtered.filter((item) => {
          // 已过期状态需要特殊处理
          if (this.currentTab === '4') {
            // 这里简单判断，实际需要根据预约时间判断
            return item.auditStatus === '1' && this.isExpired(item.appointmentDate);
          }
          return item.auditStatus === this.currentTab;
        });
        console.log('状态筛选后记录数:', filtered.length);
      }

      // 按时间筛选
      filtered = this.filterByTime(filtered);

      console.log('最终筛选结果数:', filtered.length);
      this.filteredRecords = filtered;
    },

    // 按时间筛选
    filterByTime(records) {
      console.log('========== 时间筛选开始 ==========');
      console.log('筛选条件:', this.currentTimeFilter);
      console.log('输入记录数:', records.length);

      if (this.currentTimeFilter === 'all') {
        console.log('返回全部记录');
        return records;
      }

      const now = new Date();
      let days = 7;

      if (this.currentTimeFilter === '7days') {
        days = 7;
      } else if (this.currentTimeFilter === '30days') {
        days = 30;
      } else if (this.currentTimeFilter === 'custom') {
        // 自定义时间暂时返回全部
        console.log('自定义时间，返回全部记录');
        return records;
      }

      const startDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
      console.log(`筛选最近 ${days} 天的记录`);
      console.log('起始日期:', startDate.toLocaleDateString());

      // 检查记录的日期格式
      if (records.length > 0 && records[0]) {
        console.log('第一条记录示例:', {
          createTime: records[0].createTime,
          applyNo: records[0].applyNo,
        });
      }

      const filtered = records.filter((record) => {
        if (!record.createTime) {
          return false;
        }
        // 处理iOS兼容性问题：将 'yyyy-MM-dd HH:mm:ss' 格式转换为 iOS 支持的 'yyyy/MM/dd HH:mm:ss' 格式
        const formattedDate = record.createTime.replace(/-/g, '/');
        const recordDate = new Date(formattedDate);
        return recordDate >= startDate;
      });

      console.log('输出记录数:', filtered.length);
      console.log('========== 时间筛选结束 ==========');
      return filtered;
    },

    // 判断是否过期
    isExpired(appointmentDate) {
      if (!appointmentDate) return false;
      // 处理iOS兼容性问题：将 'yyyy-MM-dd HH:mm:ss' 格式转换为 iOS 支持的 'yyyy/MM/dd HH:mm:ss' 格式
      const formattedDate = appointmentDate.replace(/-/g, '/');
      return new Date(formattedDate) < new Date();
    },

    // 显示时间选择器
    showTimePicker() {
      this.$refs.timePopup.open();
    },

    // 关闭时间选择器
    closeTimePicker() {
      this.$refs.timePopup.close();
    },

    // 选择时间选项
    selectTimeOption(option) {
      if (option.value === 'custom') {
        // TODO: 实现自定义时间选择
        uni.showToast({ title: '自定义时间功能开发中', icon: 'none' });
        this.closeTimePicker();
        return;
      }

      this.currentTimeFilter = option.value;
      this.timeFilterText = option.label;
      this.closeTimePicker();

      // 重新筛选记录
      this.page = 1;
      this.filterRecords();

      console.log('选择时间范围:', option.label, '当前筛选值:', this.currentTimeFilter);
    },

    // 选择临时时间选项
    selectTempTimeOption(option) {
      if (option.value === 'custom') {
        uni.showToast({ title: '自定义时间功能开发中', icon: 'none' });
        return;
      }
      this.tempTimeFilter = option.value;
    },

    // 确认时间筛选
    confirmTimeFilter() {
      const selectedOption = this.timeOptions.find((opt) => opt.value === this.tempTimeFilter);
      if (selectedOption) {
        this.currentTimeFilter = this.tempTimeFilter;
        this.timeFilterText = selectedOption.label;
        this.page = 1;
        this.filterRecords();
      }
      this.closeTimePicker();
    },

    // 获取临时筛选标签
    getTempFilterLabel() {
      const option = this.timeOptions.find((opt) => opt.value === this.tempTimeFilter);
      return option ? option.label : '';
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: 'status-pending',
        1: 'status-approved',
        2: 'status-inspection',
        3: 'status-rejected',
        4: 'status-expired',
      };
      return classMap[status] || 'status-pending';
    },

    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        0: 'time',
        1: 'checkmarkempty',
        3: 'closeempty',
        4: 'info',
      };
      return iconMap[status] || 'time';
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        0: '待审核',
        1: '已通过',
        2: '需抽检',
        3: '已驳回',
        4: '已过期',
      };
      return textMap[status] || '待审核';
    },

    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      // 处理iOS兼容性问题：将 'yyyy-MM-dd HH:mm:ss' 格式转换为 iOS 支持的 'yyyy-MM-ddTHH:mm:ss' 格式
      if (dateStr.includes(' ') && dateStr.includes('-') && !dateStr.includes('T')) {
        dateStr = dateStr.replace(' ', 'T');
      }
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取市场名称
    getMarketName(record) {
      return record.entryPlace || '农批市场';
    },

    // 获取产品类型
    getProductType(record) {
      if (record.purchaseType === '1') {
        return '农批市场入场销售';
      } else if (record.purchaseType === '0') {
        return '食用农产品';
      }
      return '食用农产品';
    },

    // 判断是否可以重新预约
    canReApply(status) {
      return status === '3' || status === '4'; // 已驳回或已过期
    },

    // 判断是否可以删除
    canDelete(status) {
      return status === '3' || status === '4'; // 已驳回或已过期
    },

    // 跳转到详情
    goToDetail(record) {
      uni.navigateTo({
        url: `/pages/appointment/detail?applyId=${record.applyId}`,
      });
    },

    // 重新预约
    reApply(record) {
      uni.showModal({
        title: '提示',
        content: '确定要重新发起预约申请吗？',
        success: (res) => {
          if (res.confirm) {
            // 根据类型跳转到对应的预约页面
            const url = record.purchaseType === '1' ? '/pages/appointment/market' : '/pages/appointment/food';
            uni.navigateTo({ url });
          }
        },
      });
    },

    // 删除记录
    async deleteRecord(record) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条预约记录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await delAppointment(record.applyId);
              if (response.code === 200) {
                uni.showToast({ title: '删除成功', icon: 'success' });
                this.loadRecords();
              }
            } catch (error) {
              console.error('删除失败:', error);
              uni.showToast({ title: '删除失败', icon: 'error' });
            }
          }
        },
      });
    },

    // 加载更多
    loadMore() {
      if (this.hasMore) {
        this.page++;
        this.loadRecords();
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.refresherTriggered = true;
      try {
        // 重置分页
        this.page = 1;
        this.hasMore = true;

        // 重新加载数据
        await this.loadRecords();

        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000,
        });
      } catch (error) {
        console.error('刷新失败:', error);
        uni.showToast({
          title: '刷新失败',
          icon: 'none',
          duration: 1000,
        });
      } finally {
        // 停止下拉刷新
        setTimeout(() => {
          this.refresherTriggered = false;
        }, 500);
      }
    },
  },
};
</script>

<style scoped>
.appointment-record {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 已移除header相关样式，使用系统导航栏 */

.status-tabs {
  background-color: #fff;
  height: 88rpx;
  white-space: nowrap;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.tabs-content {
  display: flex;
  padding: 0 20rpx;
}

.tab-item {
  display: inline-block;
  padding: 26rpx 32rpx;
  font-size: 30rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #1890ff;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #1890ff;
  border-radius: 3rpx;
}

.tab-text {
  white-space: nowrap;
}

.time-filter-container {
  padding: 0 30rpx;
}

.time-filter {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 20rpx;
  background-color: #f0f8ff;
  border-radius: 20rpx;
  margin: 20rpx 0;
}

.filter-text {
  font-size: 26rpx;
  color: #1890ff;
  margin: 0 8rpx;
  font-weight: 500;
}

.record-list {
  height: calc(100vh - 88rpx - 100rpx - 80rpx);
  padding: 20rpx;
}

.record-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  min-height: 160rpx;
}

.card-content {
  position: relative;
  padding: 24rpx 20rpx 20rpx 20rpx;
  min-height: 136rpx;
}

.status-badge {
  position: absolute;
  top: 0;
  left: 0;
  padding: 6rpx 16rpx;
  border-radius: 0 0 12rpx 0;
  display: flex;
  align-items: center;
  font-size: 22rpx;
}

.status-pending {
  background-color: #faad14;
}

.status-approved {
  background-color: #52c41a;
}

.status-rejected {
  background-color: #ff4d4f;
}

.status-expired {
  background-color: #8c8c8c;
}

.status-inspection {
  background-color: #1890ff;
}

.status-text {
  color: #fff;
  margin-left: 6rpx;
}

.main-content {
  padding-top: 35rpx;
  padding-right: 10rpx;
}

.record-number {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-bottom: 12rpx;
}

.market-name {
  display: block;
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.product-info {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.record-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-time {
  font-size: 24rpx;
  color: #999;
}

.product-quantity {
  font-size: 24rpx;
  color: #666;
}

.action-buttons {
  position: absolute;
  top: 35rpx;
  right: 20rpx;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 30rpx;
  height: auto;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  min-width: 60rpx;
  height: 50rpx;
  cursor: pointer;
  padding-top: 8rpx;
}

.btn-text {
  font-size: 18rpx;
  color: #666;
  margin-top: 3rpx;
  white-space: nowrap;
  text-align: center;
  line-height: 1;
  width: max-content;
}

.detail-btn .btn-text {
  color: #666;
}

.reapply-btn .btn-text {
  color: #666;
}

.delete-btn .btn-text {
  color: #ff4d4f;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 30rpx;
}

.load-more {
  text-align: center;
  padding: 30rpx;
}

.load-more-text {
  font-size: 28rpx;
  color: #666;
}

.time-picker-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.cancel-btn {
  font-size: 30rpx;
  color: #999;
}

.popup-title {
  font-size: 34rpx;
  color: #333;
  font-weight: 600;
}

.confirm-btn {
  font-size: 30rpx;
  color: #1890ff;
  font-weight: 500;
}

.time-options {
  padding: 20rpx 0;
  max-height: 600rpx;
}

.time-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 30rpx;
  transition: background-color 0.2s;
}

.time-option:active {
  background-color: #f5f5f5;
}

.time-option.active {
  background-color: #f0f8ff;
}

.option-text {
  font-size: 32rpx;
  color: #333;
}

.time-option.active .option-text {
  color: #1890ff;
  font-weight: 500;
}

.option-check {
  display: flex;
  align-items: center;
}

.current-selection {
  padding: 24rpx 30rpx;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #f0f0f0;
}

.selection-label {
  font-size: 26rpx;
  color: #999;
  margin-right: 12rpx;
}

.selection-value {
  font-size: 28rpx;
  color: #1890ff;
  font-weight: 500;
}
</style>
